// 1123. 最深叶节点的最近公共祖先
// AC: https://leetcode.cn/problems/lowest-common-ancestor-of-deepest-leaves/submissions/620270176/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode *res;
    int maxd = 0;

    int dfs(TreeNode *root, int depth) {
        if (root == nullptr)
            return depth;
        
        int l = dfs(root -> left, depth + 1);
        int r = dfs(root -> right, depth + 1);
        maxd = max(maxd, max(l, r));

        if (l == r && maxd == l)
            res = root;

        return max(l, r);
    }

    TreeNode* lcaDeepestLeaves(TreeNode* root) {
        dfs(root, 0);
        return res;
    }
};